package com.ykj.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.ykj.dto.UserMsg;
import com.ykj.entity.User;
import com.ykj.utils.MyUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ykj.utils.RedisConstants.LOGIN_TOKEN;
import static com.ykj.utils.RedisConstants.LOGIN_TOKEN_TTL;

/**
 * @author Y2014188432
 */
public class AllInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public AllInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1 获取 token
        String token = request.getHeader("Authorization");
        System.out.println("token = " + token);
        // 2 若 token 为空则，放行
        if (token == null) {
            return true;
        }
        // 3 根据 token 从 redis 中获取用户 id
        String id = stringRedisTemplate.opsForValue().get(LOGIN_TOKEN + token);
        // 4 为空则结束
        if (id == null) {
            return true;
        }
        // 5 更新有效时间
        stringRedisTemplate.expire(LOGIN_TOKEN + token,LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        // 6 存放用户 id 到 ThreadLocal
        MyUtils.add(id);
        // 7 放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
